<template>
  <div class="main_box">
    <el-row>
      <el-tabs v-model="filters.villageType" type="card" @tab-click="villageTypeChange">
        <el-tab-pane label="小区" name="2"></el-tab-pane>
        <el-tab-pane label="地区" name="4"></el-tab-pane>
        <el-tab-pane label="公里数" name="3"></el-tab-pane>
        <el-tab-pane label="专属" name="1"></el-tab-pane>
      </el-tabs>
    </el-row>
    <el-row type="flex">
      <el-col :span="3" style="padding-right: 20px">
        <div class="sidebar">
          <el-input prefix-icon="el-icon-search" placeholder="关键字搜索" v-model="businessVillageKey" size="small" @input="getBusinessVillageList" clearable> </el-input>
          <div class="sidebar-list-wrapper">
            <div class="sidebar-title">选择</div>
            <el-scrollbar class="sidebar-list">
              <ul>
                <li v-for="item in businessVillageList" :style="{ background: item.id == filters.businessVillageId ? '#F2F2F2' : '' }" class="side-list-item" @click="selectBusinessVillage(item.id)">
                  {{ item.value }}
                </li>
                <li style="color: grey; text-align: center" v-if="!businessVillageList || businessVillageList.length <= 0">暂 无 数 据</li>
              </ul>
            </el-scrollbar>
          </div>
        </div>
      </el-col>
      <el-col :span="21">
        <el-row class="header-row" style="padding-top: 0">
          <el-col>
            <div class="search_wrap">
              <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
                <el-form-item prop="goodsCode">
                  <el-input v-model="filters.goodsCode" placeholder="产品编号" clearable></el-input>
                </el-form-item>
                <el-form-item prop="name">
                  <el-input v-model="filters.name" placeholder="产品名称" clearable></el-input>
                </el-form-item>
                <el-form-item prop="classifyIds" v-if="userRole == 1">
                  <el-cascader
                    v-model="filters.classifyIds"
                    filterable
                    clearable
                    placeholder="请选择服务分类"
                    :options="serverClassifyList"
                    :props="{ checkStrictly: true, value: 'serverClassifyId', label: 'classifyName' }"
                  >
                  </el-cascader>
                </el-form-item>
                <el-form-item prop="variantState">
                  <el-select v-model="filters.variantState" clearable filterable placeholder="规格">
                    <el-option v-for="item in variantStateList" :value="item.id" :key="item.id" :label="item.name"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="businessId">
                  <el-select v-model="filters.businessId" placeholder="商户" @change="businessChange" filterable clearable>
                    <el-option v-for="item in businessList" :key="item.id" :value="item.id" :label="item.name"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="saleState">
                  <el-select v-model="filters.saleState" filterable clearable placeholder="产品状态">
                    <el-option v-for="item in $Options.saleStateList" :label="item.name" :value="item.id" :key="item.id"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="flag">
                  <el-radio-group v-model="filters.flag">
                    <el-radio :label="1"> 上门 </el-radio>
                    <el-radio :label="2"> 到店 </el-radio>
                    <el-radio :label="3"> 远程 </el-radio>
                  </el-radio-group>
                  <!-- <el-checkbox v-model="filters.visitFlag">上门</el-checkbox> -->
                </el-form-item>
                <!-- <el-form-item prop="shopFlag">
                  <el-checkbox v-model="filters.shopFlag">到店</el-checkbox>
                </el-form-item>
                <el-form-item prop="remoteFlag">
                  <el-checkbox v-model="filters.remoteFlag">远程</el-checkbox>
                </el-form-item> -->
                <el-form-item prop="fastFlag">
                  <el-checkbox v-model="filters.fastFlag">紧急通知</el-checkbox>
                </el-form-item>
                <el-form-item>
                  <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
                  <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
          <el-col>
            <div class="opration_wrap">
              <el-tooltip content="刷新" placement="top">
                <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
              </el-tooltip>
              <div>
                <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 铺货 </el-button>
                <el-button type="success" plain icon="el-icon-sell" v-has="permissionAdd" @click="handleBatchUpdateSaleState(2)" size="mini">上架 </el-button>
                <el-button type="warning" plain icon="el-icon-sold-out" v-has="permissionAdd" @click="handleBatchUpdateSaleState(3)" size="mini">下架 </el-button>
                <el-button type="info" plain icon="el-icon-s-release" v-has="permissionAdd" @click="handleBatchUpdateSaleState(4)" size="mini">售罄 </el-button>
                <el-button type="primary" icon="fa fa-link" v-has="permissionBandAttr" @click="handleBatchBindAttr()" size="mini"> 批量绑定属性 </el-button>
                <el-button type="primary" plain icon="fa fa-chain" @click="handleClickBandGoods()" size="mini"> 批量绑定产品 </el-button>
                <el-button v-has="permissionBacthSetDepart" type="info" size="mini" icon="fa fa-link" @click="handleBatchBatchSetDepart"> 批量设置部门 </el-button>
                <el-button size="mini" icon="fa fa-plus" type="primary" v-has="permissionAddGoodsCombine" @click="handleAddGoodsCombine">新增套餐产品</el-button>
                <el-button type="warning" v-has="permissioTimeTemplate" icon="el-icon-time" @click="handleSetGoodsHours()" size="mini">批量设置时间模板</el-button>

                <el-button type="danger" plain icon="el-icon-delete" v-has="permissionBatchDelete" @click="handleDeleteGoods" size="mini">一键删除 </el-button>
              </div>
            </div>
          </el-col>
        </el-row>

        <el-row ref="tableRow">
          <!-- 列表 -->
          <el-table
            ref="tableList"
            :data="dataList"
            :fit="true"
            highlight-current-row
            v-loading="listLoading"
            @row-click="$refs.tableList.toggleRowSelection($event)"
            @selection-change="handleSelectionChange"
            element-loading-text="数据加载中，请稍后..."
            empty-text="对不起，没有找到相关数据！"
          >
            <el-table-column type="selection" width="50" align="center"></el-table-column>
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column align="center" label="产品编号" prop="goodsCode"> </el-table-column>
            <el-table-column align="center" label="产品图片" width="160">
              <template slot-scope="scope">
                <el-image title="点击可预览" :src="scope.row.mainImage" fit="cover" :preview-src-list="[scope.row.mainImage]" :z-index="scope.$index"> </el-image>
              </template>
            </el-table-column>
            <el-table-column align="center" label="产品名称" prop="name"> </el-table-column>
            <el-table-column align="center" label="产品分类">
              <template slot-scope="scope"> {{ scope.row.serverClassifyName }}-{{ scope.row.thirdClassifyName }} </template>
            </el-table-column>
            <el-table-column align="center" label="规格">
              <template slot-scope="scope">
                <el-tag type="danger" size="mini" effect="dark" v-if="scope.row.goodsType == 2"> 套餐 </el-tag>
                <el-tag size="mini" type="danger" effect="dark" color="#F18311" v-else-if="scope.row.goodsType == 3"> 计时 </el-tag>
                <el-tag size="mini" type="danger" effect="dark" color="#11F127" v-else-if="scope.row.goodsType == 10"> 补贴 </el-tag>
                <el-tag size="mini" effect="dark" color="#3A7819" v-else-if="scope.row.goodsType == 15"> 补差价 </el-tag>
                <el-tag effect="dark" type="warning" size="mini" v-else-if="scope.row.huskFlag == 1"> 空包产品 </el-tag>
                <el-tag effect="dark" size="mini" v-else-if="scope.row.variantState == 1"> 单品 </el-tag>
                <el-tag type="success" size="mini" effect="dark" v-else-if="scope.row.variantState == 2"> 多规格 </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="上门/到店/远程/紧急通知" width="120">
              <template slot-scope="scope">
                <div>
                  <el-tag size="mini" effect="dark" v-if="scope.row.visitFlag == 1"> 上门 </el-tag>
                  <el-tag size="mini" effect="dark" v-if="scope.row.shopFlag == 1" type="success"> 到店 </el-tag>
                  <div></div>
                  <el-tag size="mini" effect="dark" v-if="scope.row.remoteFlag == 1" type="warning"> 远程 </el-tag>
                  <el-tag size="mini" effect="dark" v-if="scope.row.fastFlag == 1" type="danger"> 急 </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="是否需配送费">
              <template slot-scope="scope">
                <div>
                  <el-tag size="mini" effect="dark" v-if="scope.row.deliveryFlag == 0" type="info"> 否 </el-tag>
                  <el-tag size="mini" effect="dark" v-if="scope.row.deliveryFlag == 1"> 是 </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="是否隐藏">
              <template slot-scope="scope">
                <div>
                  <el-tag size="mini" effect="dark" v-if="!scope.row.showFlag" type="info"> 否 </el-tag>
                  <el-tag size="mini" effect="dark" v-if="scope.row.showFlag"> 是 </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="商户/部门" prop="businessName">
              <template slot-scope="scope">
                <div>{{ scope.row.businessName }}</div>
                <div>{{ scope.row.departName }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="原价" prop="price"></el-table-column>
            <el-table-column align="center" label="售价" prop="salePrice"></el-table-column>
            <el-table-column align="center" label="包装费" prop="packageFee"></el-table-column>
            <!--<el-table-column align="center" label="配送费" prop="deliveryFee"></el-table-column>-->
            <el-table-column align="center" label="商户折扣比例" prop="discount"></el-table-column>
            <el-table-column align="center" label="产品状态" width="100">
              <template slot-scope="scope">
                <div>
                  <el-tag :type="formatSaleStates(scope.row.saleState)" effect="dark" size="mini">
                    {{ formatSaleState(scope.row.saleState) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" width="90" label="创建时间" prop="createDate"></el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
                <el-dropdown trigger="click" size="small">
                  <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑 </el-dropdown-item>
                    <el-dropdown-item v-has="permissionBandAttr" @click.native="handleClickBandAttr(scope.row)">绑定属性 </el-dropdown-item>
                    <el-dropdown-item v-has="permissionBandGoods" @click.native="handleClickBandGoods(scope.row)">绑定产品 </el-dropdown-item>
                    <!-- <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{scope.row.state === 0 ? '启用' : '禁用'
                            }}</el-dropdown-item> -->
                    <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除 </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页工具条 -->
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.pageNo"
            :page-sizes="[20, 50, 100]"
            :page-size="page.pageSize"
            layout="total, sizes, jumper, next, pager, prev"
            :total="page.pageTotal"
          ></el-pagination>
        </el-row>
      </el-col>
    </el-row>

    <el-dialog class="custom-size__dialog" center :visible.sync="batchSetDepart.showBatchSetDepart" title="批量绑定部门">
      <el-cascader v-model="batchSetDepart.departIds" placeholder="请选择部门" :options="batchSetDepart.departList" :props="{ label: 'departName', value: 'departId', checkStrictly: true }"> </el-cascader>
      <div slot="footer">
        <el-button type="primary" @click="confirmBatchSetDepart">确定</el-button>
        <el-button @click="batchSetDepart.showBatchSetDepart = false">取消</el-button>
      </div>
    </el-dialog>
    <!-- 绑定时间-->
    <el-dialog center :visible.sync="hoursModel.show" title="设置可售时间" width="fit-content">
      <el-select v-model="hoursModel.ghModelId" placeholder="请选择可售时间模板" @change="handleGhModelIdChange">
        <el-option v-for="item in hoursModel.relationsList" :label="item.modelName" :value="item.modelId" :key="item.modelId"> </el-option>
      </el-select>
      <el-table :data="hoursModel.relations" style="width: fit-content; max-width: fit-content; margin-top: 10px">
        <el-table-column type="index" label="序号" align="center" width="100px"> </el-table-column>
        <el-table-column prop="beginHours" label="开始时间" align="center" width="200"> </el-table-column>
        <el-table-column prop="endHours" label="结束时间" align="center" width="200"> </el-table-column>
        <el-table-column prop="estimateTime" label="最快到达时间" align="center" width="200">
          <template slot-scope="scope"> {{ scope.row.estimateTime }}{{ formatTimeUnit(scope.row.timeUnit) }} </template>
        </el-table-column>
        <el-table-column prop="deliveryTime" label="可送时间段" align="center" width="200"> </el-table-column>
        <el-table-column prop="businessRemindTime" label="商户提醒时间(分)" align="center" width="140"> </el-table-column>
        <el-table-column prop="waiterRemindTime" label="服务员提醒时间(分)" align="center" width="140"> </el-table-column>
      </el-table>
      <div slot="footer">
        <el-button type="primary" @click="confirmSetGoodsHours">确定</el-button>
        <el-button @click="hoursModel.show = false">取消</el-button>
      </div>
    </el-dialog>
    <business-server-select ref="businessServerSelect" :business-id="filters.businessId" @getServerList="getCopyServerList"></business-server-select>

    <BindAttr ref="bindAttr" />
    <BindGoods :show="bandGoodsParam.show" :id-type="2" :goodsIds="bandGoodsParam.goodsIds" :id="bandGoodsParam.id" @cancel="cancelBandGoods" />
  </div>
</template>
<script>
import GoodsApi from '@/api/goods/goods';
import BusinessApi from '@/api/business/business';
import BusinessVilageApi from '@/api/business/businessVillage';
import ServerClassifyApi from '@/api/server/serverClassify';
import BusinessDepartApi from '../../api/business/depart';
import BindAttr from '../../components/BindAttr.vue';
import BusinessServerSelect from '../../components/BusinessServerSelect.vue';
import ActiveVillage from './components/ActiveVillage.vue';
import * as message from '@/constants/message';
import BindGoods from '../../components/BindGoods.vue';
import { getStorage } from '@/utils/auth';
import { USER_INFO } from '@/constants/storeName';
import businessServerApi from '@/api/goods/businessServer';
import ActiveApi from '@/api/operation/active';
import TimeTemplateApi from '@/api/goods/timeTemplate';
import GoodRelationApi from '@/api/goods/goodRelation';
export default {
  name: 'GoodsManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      userRole: '',
      dataList: [],
      listLoading: false,
      imgList: [], //产品图片
      filters: {
        villageType: '2',
        businessVillageId: '',
        classifyIds: [],
        goodsCode: '',
        variantState: '',
        name: '',
        businessId: '',
        // visitFlag: false,
        // shopFlag: false,
        // remoteFlag: false,
        fastFlag: false,
        flag: '',
        saleState: '', //1 待上架 2上架 3下架 4当日售罄
      },
      selectedForm: {
        ids: [],
        businessIds: [],
        state: '',
      },
      bandGoodsParam: {
        show: false,
        id: '',
        goodsIds: [],
      },
      businessList: [],
      serverClassifyList: [],
      variantStateList: [
        { id: 1, name: '单品' },
        { id: 2, name: '多规格' },
        { id: 3, name: '套餐' },
        { id: 4, name: '空包产品' },
        { id: 5, name: '计时' },
        { id: 6, name: '补贴' },
        { id: 7, name: '补差价' },
      ],
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },

      permissionAdd: 'SYSTEM_MANAGER_GOODS_INFO_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_GOODS_INFO_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_GOODS_INFO_LIST_EDIT',
      permissionDelete: 'SYSTEM_MANAGER_GOODS_INFO_LIST_DELETE',
      permissionBandAttr: 'SYSTEM_MANAGER_GOODS_INFO_LIST_BAND_ATTR',
      permissionBandGoods: 'SYSTEM_MANAGER_GOODS_INFO_LIST_BAND_GOODS',
      permissionBatchDelete: 'SYSTEM_MANAGER_GOODS_INFO_LIST_BATCH_DELETE',
      permissionBacthSetDepart: 'SYSTEM_MANAGER_GOODS_INFO_LIST_BATCH_SET_DEPART',
      permissionAddGoodsCombine: 'SYSTEM_MANAGER_GOODS_INFO_LIST_ADD_GOODS_COMBINE',
      permissioTimeTemplate: 'SYSTEM_MANAGER_GOODS_INFO_LIST_TIME_TEMPLATE',
      activeName: '1',
      businessVillageKey: '',
      businessVillageList: [],
      batchSetDepart: {
        showBatchSetDepart: false,
        departIds: [],
        departList: [],
      },
      hoursModel: {
        show: false,
        relations: [],
        ghModelId: '',
        relationsList: [],
      },
    };
  },
  updated() {},
  components: {
    BusinessServerSelect,
    BindGoods,
    BindAttr,
    ActiveVillage,
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    if (this.$route.query.businessId) {
      // 从其它的地方进来
      this.filters.businessId = this.$route.query.businessId;
    }
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      // 获取用户的角色信息
      this.userRole = this.$store.getters.userRole;
      // if (this.userRole == 3) {
      //   this.listLoading = true
      //   this.filters.businessId = this.$store.getters.relationRoleId
      //   this.listData();
      //   this.getBusinessVillageList()
      // } else if (this.userRole == 1) {

      // }
      this.getBusinessList();
      this.getServerClassifyList();
      this.getTableHeight();
      // this.getDepartList()
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    getTableHeight() {
      let sideBar = document.getElementsByClassName('sidebar')[0];
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 200;
        sideBar.style.height = window.innerHeight - sideBar.pageX;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 200;
          sideBar.style.height = window.innerHeight - sideBar.pageX;
        };
      });
    },
    handleBatchUpdateSaleState(state) {
      if (this.selectedForm.ids.length <= 0) {
        this.$message({
          type: 'warning',
          message: '请只少选择一项',
        });
        return;
      }
      let msg = null;
      if (state == 2) msg = '上架';
      if (state == 3) msg = '下架';
      if (state == 4) msg = '售罄';
      this.$confirm(`确认${msg}产品吗？`, '提示', {
        type: 'warning',
      }).then((res) => {
        this.selectedForm.state = state;
        GoodsApi.batchUpdateSaleState(this.selectedForm).then((data) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    handleDeleteGoods() {
      if (!this.filters.businessVillageId && this.selectedForm.ids.length == 0) {
        this.$message.error('请选择经营区域或者至少勾选一项产品');
        return;
      }
      if (this.dataList.length == 0) {
        this.$message.warning('该经营区域下没有产品');
        return;
      }
      this.$confirm('确认一键删除' + this.selectedForm.ids.length > 0 ? '勾选的产品吗？' : '该经营区域下的全部产品吗？', '提示', {})
        .then((res) => {
          let params = {
            businessVillageId: this.filters.businessVillageId,
            goodsIds: this.selectedForm.ids,
          };
          GoodsApi.batchDelete(params).then((res) => {
            this.$Utils.notifySuccess('删除成功');
            this.listData();
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleBatchBatchSetDepart() {
      const { ids, businessIds } = this.selectedForm;
      if (ids == 0) {
        this.$message.error('请至少选择一项');
        return;
      }
      if (Array.from(new Set(businessIds)).length > 1) {
        this.$message.error('只能选择相同的商户');
        return;
      }
      BusinessDepartApi.listMangerTree({ businessId: businessIds[0] }).then((res) => {
        this.setDisabled(res.data);
        this.batchSetDepart.departList = res.data;
        this.batchSetDepart.departIds = [];
        this.batchSetDepart.showBatchSetDepart = true;
      });
    },
    setDisabled(list) {
      list.forEach((item) => {
        if (!item.power) {
          item.disabled = true;
        }
        if (item.children) {
          this.setDisabled(item.children);
        }
      });
    },
    confirmBatchSetDepart() {
      const departIds = this.batchSetDepart.departIds;
      const { ids, businessIds } = this.selectedForm;
      const params = {
        ids,
        departId: departIds[0] || '',
        firstDepartId: departIds[1] || '',
        secondDepartId: departIds[2] || '',
        thirdDepartId: departIds[3] || '',
        businessId: businessIds[0],
      };
      this.$confirm('确认批量设置部门吗？', '提示', {}).then(() => {
        GoodsApi.batchSetDepart(params).then(() => {
          this.batchSetDepart.showBatchSetDepart = false;
          this.$Utils.notifySuccess('批量绑定成功');
          this.listData();
        });
      });
    },
    handleSetGoodsHours() {
      const { hoursModel, selectedForm } = this;
      if (!selectedForm.ids.length) {
        this.$message.error('至少选择一项');
        return;
      }

      TimeTemplateApi.listIdName({ businessId: selectedForm.businessIds[0] }).then((res) => {
        hoursModel.relationsList = res.data;
      });
      hoursModel.ghModelId = '';
      hoursModel.relations = [];
      hoursModel.show = true;
    },
    formatTimeUnit(cell) {
      if (cell == 1) {
        return '分钟';
      } else if (cell == 2) {
        return '时';
      } else {
        return '';
      }
    },
    handleGhModelIdChange() {
      const { ghModelId, relationsList } = this.hoursModel;
      if (!ghModelId) {
        this.hoursModel.relations = [];
        return;
      } else {
        const val = relationsList.find((item) => item.modelId == ghModelId);
        if (val) {
          this.hoursModel.relations = val.relations;
        }
      }
      console.log(this.hoursModel.relations);
    },
    confirmSetGoodsHours() {
      const { selectedForm, hoursModel } = this;
      if (!hoursModel.ghModelId) {
        this.$message.error('请选择可售时间模板');
        return;
      }
      const params = {
        goodsIds: selectedForm.ids,
        ghModelId: hoursModel.ghModelId,
      };
      this.$confirm('确定设置可售时间吗？', '提示', {}).then(() => {
        TimeTemplateApi.batchSetModel(params).then(() => {
          this.listData();
          this.$Utils.notifySuccess('设置成功');
          hoursModel.show = false;
        });
      });
    },
    handleAddGoodsCombine() {
      const { businessId, businessVillageId } = this.filters;
      if (!this.filters.businessId) {
        this.$message.error('请选择商户');
        return;
      }

      if (!this.filters.businessVillageId) {
        this.$message.error('请选择经营范围');
        return;
      }
      this.$router.push({
        name: '新增套餐组合',
        params: {
          businessId,
          businessVillageId,
          businessVillageName: this.businessVillageList.find((item) => item.id == businessVillageId).value,
        },
      });
    },
    handleSelectionChange(value) {
      this.selectedForm.ids = value.map((item) => item.goodsId);
      this.selectedForm.businessIds = value.map((item) => item.businessId);
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickAdd() {
      if (!this.filters.businessId) {
        this.$message({
          type: 'warning',
          message: '请选择商户',
        });
        return;
      }
      if (!this.filters.businessVillageId) {
        this.$message({
          type: 'warning',
          message: '请选择经营范围',
        });
        return;
      }
      this.$refs.businessServerSelect.handleCreate(this.filters.businessVillageId);
    },
    handleClickBandAttr(row) {
      this.$refs.bindAttr.handleCreate({ type: 4, id: row.goodsId, businessId: row.businessId });
    },
    handleBatchBindAttr() {
      if (this.selectedForm.ids == 0) {
        this.$message.error('请至少选择一项');
        return;
      }
      this.$refs.bindAttr.handleCreate({ type: 4, ids: this.selectedForm.ids });
    },
    // async handleBatchBindGoods(){
    //   if (this.selectedForm.ids == 0) {
    //     this.$message.error("请至少选择一项")
    //     return
    //   }
    //   await this.$confirm("确认批量绑定","提示",{})
    //   await GoodRelationApi.bandRelation({goodsIds:this.selectedForm.ids})
    //   this.$Utils.notifySuccess("绑定成功")
    // },
    handleClickBandGoods(row) {
      if (!row) {
        // 批量绑定
        if (this.selectedForm.ids == 0) {
          this.$message.error('请至少选择一项');
          return;
        }
        this.bandGoodsParam.id = '';
        this.bandGoodsParam.goodsIds = this.selectedForm.ids;
      } else {
        this.bandGoodsParam.id = row.goodsId;
        this.bandGoodsParam.goodsIds = [];
      }
      this.bandGoodsParam.show = true;
    },
    cancelBandGoods() {
      this.bandGoodsParam.show = false;
    },
    getCopyServerList(val) {
      let params = {
        serverIds: val.map((item) => item.serverId),
        businessVillageIds: [this.filters.businessVillageId],
        saleState: 2,
        businessId: this.filters.businessId,
      };
      businessServerApi.setDistribution(params).then((res) => {
        this.$Utils.notifySuccess();
        this.listData();
      });
    },
    handleClickEditor(row) {
      if (row.goodsType == 2) {
        this.$router.push({
          name: '新增套餐组合',
          query: { id: row.goodsId },
          params: {
            businessVillageId: this.filters.businessVillageId,
          },
        });
        // this.$router.push({
        //   path: '/goods/goodsComboEdit',
        //   query:
        // })
      } else {
        this.$router.push({
          path: '/goods/goodsEdit',
          query: { id: row.goodsId },
        });
      }
    },
    handleClickDetail(row) {
      this.$router.push({
        path: row.goodsType == 2 ? '/goods/goodsComboDetail' : '/goods/goodsDetail',
        query: { id: row.goodsId },
      });
    },
    handleIsDisable(row) {
      let _this = this;
      let currentState = row.state === 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        GoodsApi.deleteGoods({
          id: row.goodsId,
          state: currentState,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    handleClickDelete(val) {
      let _this = this;
      _this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        GoodsApi.deleteGoods({
          id: val.goodsId,
          state: -1,
        }).then((res) => {
          this.$Utils.notifySuccess();
          _this.listData();
        });
      });
    },
    resetForm() {
      this.filters.villageType = '1';
      this.filters.businessVillageId = '';
      this.businessVillageKey = '';
      this.businessVillageList = [];
      this.$refs.searchForm.resetFields();
    },
    onSearch() {
      // 如果没有选择商户就不能获取列表
      if (!this.filters.businessId) {
        this.$message({
          type: 'warning',
          message: '请选择商户',
        });
        return;
      }
      this.page.pageNo = 1;
      this.listData();
    },
    formatSaleStates(val) {
      switch (val) {
        case 1:
          return '';
        case 2:
          return 'success';
        case 3:
          return 'info';
        case 4:
          return 'danger';
      }
    },
    formatSaleState(val) {
      switch (val) {
        case 1:
          return '待上架';
        case 2:
          return '上架';
        case 3:
          return '下架';
        case 4:
          return '当日售罄';
      }
    },
    // villageType改变
    villageTypeChange(e) {
      // 没拿到商户ID 提示
      if (!this.filters.businessId) {
        this.$message.warning('请先选择商户');
        return;
      }
      this.filters.businessVillageId = '';
      this.getBusinessVillageList();
    },
    // 获取商户经营列表
    getBusinessVillageList() {
      // if(!this.filters.businessId){
      //   this.$message({
      //     type:"warning",
      //     message:"请选择商户"
      //   })
      //   return
      // }
      let params = {
        villageType: this.filters.villageType,
        name: this.businessVillageKey,
        businessId: this.filters.businessId,
        // businessVillage:this.businessVillageKey
      };
      BusinessVilageApi.listIdName(params).then((res) => {
        this.businessVillageList = res.data;
      });
    },
    // 选中buseinssVillage
    selectBusinessVillage(val) {
      this.filters.businessVillageId = val;
      this.listData();
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then((res) => {
        this.businessList = res.data;
      });
    },
    //商户改变
    businessChange() {
      this.filters.villageType = '2';
      this.filters.businessVillageId = '';
      this.businessVillageKey = '';
      this.businessVillageList = [];
      if (this.filters.businessId) {
        this.getBusinessVillageList();
      }
    },
    // 获取产品分类列表
    getServerClassifyList() {
      ServerClassifyApi.listServerClassify({ level: 2 }).then((res) => {
        this.serverClassifyList = res.data;
      });
    },
    listData() {
      // 获取列表数据
      let _this = this;
      // 没有选择商户或者经营范围就不请求数据
      if (!_this.filters.businessId) return;

      _this.listLoading = true;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
      };
      cond.name = _this.filters.name;
      cond.businessId = _this.filters.businessId;
      cond.businessVillageId = _this.filters.businessVillageId;
      cond.serverClassifyId = _this.filters.classifyIds[0] ? this.filters.classifyIds[0] : '';
      cond.thirdClassifyId = _this.filters.classifyIds[1] ? this.filters.classifyIds[1] : '';
      cond.goodsCode = _this.filters.goodsCode;

      // cond.visitFlag = _this.filters.visitFlag ? 1 : ''
      // cond.shopFlag = _this.filters.shopFlag ? 1 : ''
      // cond.remoteFlag = _this.filters.remoteFlag ? 1 : ''

      cond.fastFlag = _this.filters.fastFlag ? 1 : '';
      cond.saleState = _this.filters.saleState;
      cond.villageType = _this.filters.villageType;
      if (_this.filters.flag == 1) cond.visitFlag = 1;
      if (_this.filters.flag == 2) cond.shopFlag = 1;
      if (_this.filters.flag == 3) cond.remoteFlag = 1;

      if (_this.filters.variantState == 3) {
        cond.goodsType = 2;
      } else if (this.filters.variantState == 4) {
        cond.huskFlag = 1;
      } else if (this.filters.variantState == 5) {
        cond.goodsType = 3;
      } else if (this.filters.variantState == 6) {
        cond.goodsType = 10;
      } else if (this.filters.variantState == 7) {
        cond.goodsType = 15;
      } else {
        cond.variantState = _this.filters.variantState;
      }
      GoodsApi.listGoods(cond)
        .then((res) => {
          _this.dataList = res.data.list;
          _this.page.pageTotal = res.data.total;
          _this.imgList = res.data.list.map((item) => item.mainImage);
          _this.$refs.tableList.bodyWrapper.scrollTop = 0;
          _this.listLoading = false;
          setTimeout(() => {
            _this.$refs.tableList.doLayout();
          });
        })
        .catch((err) => {
          _this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
<style lang="scss" scoped>
.img-wrapper {
  width: 80px;
  height: 60px;
  overflow: hidden;
  border-radius: 3px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin: 0 auto;

  .el-image {
    width: 100%;

    &::v-deep img {
      width: 100%;
      height: auto;
    }
  }
}

.el-tabs {
  ::v-deep .is-active {
    position: relative;

    &::after {
      position: absolute;
      content: '';
      width: 100%;
      height: 3px;
      background-color: #0064c8;
      left: 0;
    }
  }
}

.sidebar {
  height: 100%;
  font-size: 14px;
  display: flex;
  flex-direction: column;

  .el-input {
    margin-bottom: 11px;
  }

  .sidebar-list-wrapper {
    border: 1px solid #f2f2f2;
    min-height: 600px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .sidebar-title {
      text-align: center;
      line-height: 44px;
      background-color: #f2f2f2;
    }

    .sidebar-list {
      ::v-deep .el-scrollbar__wrap {
        overflow-x: hidden;
      }

      flex: 1;

      ul {
        padding: 0;
        list-style: none;

        li {
          padding: 5px 10px;
          cursor: pointer;
          // padding: 10px;
        }
      }
    }
  }
}
</style>
